<template>
  <div class="app-container">
    <box-card class="box-card-info">
      <div class="info">
        <div class="title">
          <svg-icon class-name="icon-qi" icon-class="icon-qi"></svg-icon>
          <span class="p1">江西某某建筑工程有限公司</span>
        </div>
        <ul class="data-info">
          <li>
            <img class="icon" src="@/assets/images/firm-manage/1.png" />
            <div class="sub">
              <div class="text">当前员工</div>
              <div class="num">{{ companyMealInfo.staffQty }}</div>
            </div>
          </li>
          <li>
            <img class="icon" src="@/assets/images/firm-manage/2.png" />
            <div class="sub">
              <div class="text">领取联系方式</div>
              <div class="num">{{ companyMealInfo.claimContactQuota }}</div>
            </div>
          </li>
          <li>
            <img class="icon" src="@/assets/images/firm-manage/3.png" />
            <div class="sub">
              <div class="text">公海池领取资质</div>
              <div class="num">{{ companyMealInfo.claimQualificationQty }}</div>
            </div>
          </li>
          <li>
            <img class="icon" src="@/assets/images/firm-manage/4.png" />
            <div class="sub">
              <div class="text">公海池领取证书</div>
              <div class="num">{{ companyMealInfo.claimCertificateQty }}</div>
            </div>
          </li>
        </ul>
      </div>
      <div class="member-info">
        <div class="member-header">
          <div class="title">
            <img class="icon" src="@/assets/images/firm-manage/5.png" />
            <span>{{ companyMealInfo.mealName }}</span>
          </div>
          <div class="time">剩余<span>{{ remainingDays + '天' || '' }}({{ companyMealInfo.validDate }})</span>到期</div>
        </div>
        <div class="member-body">
          <div>
            <label>员工限额</label>
            <span>{{ companyMealInfo.staffQty }}/{{ companyMealInfo.staffQuota }}</span>
          </div>
          <div>
            <label>领取联系方式限额</label>
            <span>{{ companyMealInfo.claimContactQty }}/{{ companyMealInfo.claimContactQuota }}</span>
          </div>
          <div>
            <label>公海池领取限额</label>
            <span>{{ companyMealInfo.claimQualificationQty }}/{{ companyMealInfo.claimQualificationQuota }}(资质)</span>
            <span>{{ companyMealInfo.claimCertificateQty }}/{{ companyMealInfo.claimCertificateQuota }}(证书)</span>
          </div>
        </div>
      </div>
    </box-card>

    <box-card class="box-card-query mt24">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-row>
          <el-col :span="8" class="table-title">
            <span class="title">员工设置</span>
          </el-col>
          <el-col :span="16" class="flex justify-end">
            <div class="flex justify-end">
              <el-button type="primary" @click="handleAdd">新增</el-button>
              <el-input v-model="queryParams.keywords" placeholder="请输入关键词" clearable
                style="width: 240px; margin-left: 15px;" @keyup.enter="handleQuery" />
              <el-button class="ml10" type="primary" icon="Search" @click="handleQuery">查看</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-table class="mt15" v-loading="loading" :data="dataList" stripe>
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="部门" prop="dept" />
        <el-table-column label="职位" prop="job" />
        <el-table-column label="姓名" prop="realname" />
        <el-table-column label="性别" prop="sex">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" />
        <el-table-column label="在职状态" prop="jobState">
          <template #default="scope">
            <div>{{ scope.row.jobState == 1 ? '是' : '否' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="管理员" prop="isAdmin">
          <template #default="scope">
            <div>{{ scope.row.isAdmin === 1 ? '是' : '否' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <div>{{ scope.row.status == 1 ? '启用' : '禁用' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="140" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="scope.row.isAdmin !== 1" link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.isAdmin !== 1 && scope.row.status == 1" link type="primary"
              @click="handleEnable(scope.row)">禁用</el-button>
            <el-button v-if="scope.row.isAdmin !== 1 && scope.row.status != 1" link type="primary"
              @click="handleEnable(scope.row)">启用</el-button>
            <el-button v-if="scope.row.isAdmin !== 1" link type="primary"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </box-card>

    <el-dialog :title="editTitle" v-model="open" width="900px" :align-center="true" append-to-body>
      <el-form :model="form" :rules="rules" ref="formRef" :inline="true" label-width="100">
        <el-row>
          <el-col :span="8" class="sub-title">
            <svg-icon class-name="arrow-left" icon-class="arrow-left"></svg-icon>
            <span class="title">基本信息</span>
          </el-col>
        </el-row>
        <el-row class="mt24">
          <el-col :span="12">
            <el-form-item label="姓名" prop="realname">
              <el-input v-model="form.realname" placeholder="请输入姓名" clearable style="min-width: 320px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="dict in sys_user_sex" :key="dict.value" :value="Number(dict.value)">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="dept">
              <el-input v-model="form.dept" placeholder="请输入部门" clearable style="min-width: 320px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="job">
              <el-input v-model="form.job" placeholder="请输入职位" clearable style="min-width: 320px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号" maxlength="11" clearable style="min-width: 320px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" show-password clearable style="min-width: 320px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" clearable style="min-width: 320px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在职状态" prop="jobState">
              <el-radio-group v-model="form.jobState">
                <el-radio v-for="dict in jobStatusList" :key="dict.value" :value="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusList" :key="dict.value" :value="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessageBox } from "element-plus"
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance()
import { getStaffList, getCompanyMealInfo, addStaff, editStaff, staffInfo, removeSatff } from '@/api/member'
const { sys_user_sex } = proxy.useDict("sys_user_sex")

const jobStatusList = ref([{
  label: '是',
  value: 1,
}, {
  label: '否',
  value: 0,
}])

const statusList = ref([{
  label: '有效',
  value: 1,
}, {
  label: '无效',
  value: 0,
}])

const loading = ref(false)
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  keywords: null, // 关键字
})
const dataList = ref([])
const companyMealInfo = ref({})
const remainingDays = ref(0) // 剩余天数
const open = ref(false)
const editTitle = ref('新增员工')
const submitLoading = ref(false)
const form = ref({
  avatar: undefined,
  dept: undefined,
  email: undefined,
  id: undefined,
  job: undefined,
  jobState: 1,
  mobile: undefined,
  password: undefined,
  realname: undefined,
  sex: 0,
  status: 1,
})
const rules = {
  // password: [{ required: true, trigger: "blur", message: "请输入密码" }],
  dept: [{ required: true, trigger: "blur", message: "请输入部门" }],
  email: [
    { required: true, message: "邮箱地址不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
  ],
  job: [{ required: true, trigger: "blur", message: "请输入职位" }],
  jobState: [{ required: true, trigger: "change", message: "请选择在职状态" }],
  realname: [{ required: true, trigger: "blur", message: "请输入姓名" }],
  sex: [{ required: true, trigger: "change", message: "请选择性别" }],
  status: [{ required: true, trigger: "change", message: "请选择状态" }],
  mobile: [
    { required: true, trigger: "blur", message: "请输入联系方式" },
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
}

function getList() {
  getStaffList(queryParams.value).then(res => {
    loading.value = false
    dataList.value = res.data.list
    total.value = res.data.total
  })
}

function fetchCompanyMealInfo() {
  getCompanyMealInfo().then(res => {
    if (res.code) {
      companyMealInfo.value = res.data
      let endDate = companyMealInfo.validDate
      const currentDate = dayjs().format('YYYY-MM-DD')
      remainingDays.value = calculateRemainingDays(currentDate, endDate)
    }
  })
}

function calculateRemainingDays(currentDate, endDate) {
  const diffInMilliseconds = dayjs(endDate).endOf('day').diff(dayjs(currentDate).startOf('day'))
  const remainingDays = Math.ceil(diffInMilliseconds / (1000 * 60 * 60 * 24))
  return remainingDays
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
function reset() {
  proxy.resetForm("formRef")
}
// 新增
function handleAdd() {
  reset()
  editTitle.value = '新增员工'
  open.value = true
}
// 取消
function cancelDialog() {
  open.value = false
  submitLoading.value = false
  reset()
}
// 提交
function submitForm() {
  console.log('form.value:', form.value)
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      submitLoading.value = true
      if (form.value.id) {
        editStaff(form.value).then(res => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess(res.data)
            cancelDialog()
            getList()
          }
        }).catch(() => {
          submitLoading.value = false
        })
      } else {
        addStaff(form.value).then(res => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess(res.data)
            cancelDialog()
            getList()
          }
        }).catch(() => {
          submitLoading.value = false
        })
      }
    }
  })
}
// 编辑
async function handleEdit(item) {
  reset()
  const res = await staffInfo(item.id)
  form.value = res.data
  editTitle.value = '编辑员工'
  open.value = true
  console.log('form.value:', form.value)
}
// 启用
function handleEnable(item) {
  const status = item.status === 1 ? 0 : 1
  editStaff({
    id: item.id,
    status,
  }).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(status === 1 ? '启用成功' : '禁用成功')
      getList()
    }
  })
}
// 删除
function handleDelete(item) {
  ElMessageBox.confirm(`你是否确认删除："姓名：${item.realname}" 的员工信息？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removeSatff(item.id).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.data)
        getList()
      }
    })
  }).catch(() => { })
}


getList()
fetchCompanyMealInfo()
</script>

<style lang="scss" scoped>
.sub-title {
  display: flex;
  align-items: center;
  font-size: 14px;

  .title {
    color: #333333;
    margin-left: 7px;
    margin-right: 5px;
  }
}

.box-card-query {
  .table-title {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 500;

    .title {
      color: #333333;
      margin-left: 7px;
      margin-right: 5px;
    }
  }
}

.box-card-info {
  :deep(.box-card-body) {
    display: flex;
  }

  .title {
    display: flex;
    align-items: center;
  }

  .icon-qi {
    width: 22px;
    height: 22px;
  }

  .p1 {
    color: #222222;
    font-size: 24px;
    font-weight: 500;
    margin-left: 7px;
  }

  .info {
    flex: 1;
    margin-right: 20px;
  }
}

.data-info {
  border-radius: 7px;
  background: linear-gradient(180deg, rgba(255, 248, 247, 1) 0%, rgba(255, 255, 255, 1) 100%);
  box-shadow: -4px 8px 22px rgba(242, 242, 242, 1);
  display: flex;
  justify-content: center;
  align-items: center;
  list-style: none;
  margin: 25px 0 0;

  li {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30px 0;
    margin-left: 25px;

    &:first-child {
      margin-left: 0;
    }
  }

  .sub {
    .text {
      color: #646566;
      font-size: 14px;
    }

    .num {
      color: #323233;
      font-size: 28px;
    }
  }

  .icon {
    width: 52px;
    height: 52px;
    margin-bottom: -10px;
  }
}

.member-info {
  border-radius: 12px;
  background: linear-gradient(130.67deg, rgba(255, 244, 232, 1) 0%, rgba(255, 250, 240, 1) 22.31%, rgba(255, 235, 196, 1) 100%);
  width: 374px;

  .member-header {
    border-bottom: 1px solid rgba(66, 18, 4, 0.09);
    padding-bottom: 12px;
    padding-top: 21px;
    margin-left: 16px;
    margin-right: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title {
      display: flex;

      .icon {
        width: 39px;
        height: 33px;
      }

      span {
        color: #421204;
        font-size: 18px;
        font-weight: 500;
      }
    }

    .time {
      color: #000;
      font-size: 14px;

      span {
        color: #aa261d;
      }
    }
  }

  .member-body {
    color: #421204;
    font-size: 16px;
    padding-top: 8px;
    padding-left: 16px;
    padding-right: 16px;
    padding-bottom: 24px;

    >div {
      line-height: 22px;
      margin-top: 4px;
    }

    label {
      display: inline-flex;
      color: #5e473c;
      font-weight: 400;
      width: 136px;
    }

    span {
      margin-left: 10px;
    }
  }
}
</style>